package com.demo.youxuanmall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.youxuanmall.entity.Address;
import com.demo.youxuanmall.mapper.AddressMapper;
import com.demo.youxuanmall.service.AddressService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {

    @Override
    public List<Address> getUserAddresses(Long userId) {
        return list(new LambdaQueryWrapper<Address>()
                .eq(Address::getUserId, userId)
                .eq(Address::getIsDeleted, 0)
                .orderByDesc(Address::getIsDefault)
                .orderByDesc(Address::getUpdateTime));
    }

    @Override
    @Transactional
    public void addAddress(Address address) {
        // 如果设置为默认地址，需要将其他地址设置为非默认
        if (address.getIsDefault() != null && address.getIsDefault() == 1) {
            update().set("is_default", 0)
                    .eq("user_id", address.getUserId())
                    .update();
        } else {
            // 如果用户没有选择默认地址，设置为非默认
            address.setIsDefault(0);
        }
        save(address);
    }

    @Override
    @Transactional
    public void updateAddress(Address address) {
        // 如果设置为默认地址，需要将其他地址设置为非默认
        if (address.getIsDefault() == 1) {
            update().set("is_default", 0)
                    .eq("user_id", address.getUserId())
                    .update();
        }
        updateById(address);
    }

    @Override
    @Transactional
    public void deleteAddress(Long id) {
        // 逻辑删除
        update().set("is_deleted", 1)
                .eq("id", id)
                .update();
    }

    @Override
    @Transactional
    public void setDefaultAddress(Long userId, Long addressId) {
        if (userId == null || addressId == null) {
            throw new IllegalArgumentException("用户ID和地址ID不能为空");
        }
        
        // 先检查地址是否属于该用户
        Address address = getById(addressId);
        if (address == null) {
            throw new IllegalArgumentException("地址不存在");
        }
        
        if (!userId.equals(address.getUserId())) {
            throw new IllegalArgumentException("无权操作此地址");
        }
        
        // 先将所有地址设置为非默认
        update().set("is_default", 0)
                .eq("user_id", userId)
                .eq("is_deleted", 0)
                .update();
                
        // 将指定地址设置为默认
        update().set("is_default", 1)
                .eq("id", addressId)
                .update();
    }
} 